<?php

namespace app\admin\controller;

use app\admin\event\Dt;
use app\admin\event\Utils;
use app\common\event\Tool;
use think\Db;
use think\facade\Request;

class Wechat extends Base
{
    public function index()
    {
        if(Request::isPost()){
            $dt = new Dt();
            $data = $dt->table('wechat')->searchField('name,appid')->fetch();
            foreach ($data['data'] as &$v){
                $editAction   = url('edit',['id'=>$v['id']]);
                $removeAction = url('del',['id'=>$v['id']]);
                $showAccInfo  = url('accInfo',['id'=>$v['id']]);
                $v['status']  = $v['status']?'开启':'关闭';
                $v['qr_code'] = sprintf('<img style="width:100px;" src="https://open.weixin.qq.com/qr/code?username=%s">',$v['wechat_id']);
                $v['buttons'] = sprintf('<a href="#" class="btn-edit" data-action="%s"><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a href="#" class="btn-remove" data-action="%s"><i class="fa fa-remove"></i></a>&nbsp;&nbsp;<a href="#" class="btn-show-info" data-action="%s"><i class="fa fa-info-circle"></i></a>',$editAction,$removeAction,$showAccInfo);
            }
            exit(json_encode($data));
        }

        $tColumns = [
            ['data'=>'id','title'=>'自动编号','orderable'=>true],
            ['data'=>'name','title'=>'公众号名称','orderable'=>false],
            ['data'=>'appid','title'=>'appid','orderable'=>false],
            ['data'=>'qr_code','title'=>'微信二维码','orderable'=>false],
            ['data'=>'status','title'=>'状态'],
            ['data'=>'add_time','title'=>'添加时间'],
            ['data'=>'buttons','title'=>'操作','orderable'=>false],
        ];
        $this->assign(['columns'=>json_encode($tColumns)]);
        return view();
    }

    public function edit()
    {
        if(Request::isPost()){
            $params = Request::param();
            $res = ['success'=>0,'msg'=>'请填写完整后再提交'];
            if($params['name'] && $params['appid'] && $params['appsecret']){
                $id = $params['id'];
                try{
                    $data = [
                        'name'  => trim($params['name']),
                        'appid' => trim($params['appid']),
                        'appsecret'   => trim($params['appsecret']),
                        'wechat_id'   => trim($params['wechat_id']),
                        'update_time' => date('Y-m-d H:i:s'),
                        'status' => $params['status'],
                        'token'  => $params['token'] ?? Tool::gStr(32),
                        'encode_asc_key' => $params['encode_asc_key']
                    ];
                    if(!$id){
                        $data['add_time'] = date('Y-m-d H:i:s');
                        $res = ['success'=>0,'msg'=>'添加失败，请重试'];
                        if(Db::table('wechat')->insert($data)){
                            $res = ['success'=>1,'msg'=>'添加成功'];
                        }
                    }else{
                        $res = ['success'=>0,'msg'=>'更新失败，请重试'];
                        if(Db::table('wechat')->where('id',$id)->update($data)){
                            $res = ['success'=>1,'msg'=>'更新成功'];
                        }
                    }
                }catch (\Exception $e){
                    $res = ['success'=>0,'msg'=>'操作失败，请稍后再试','err'=>$e->getMessage()];
                }
            }
            Utils::ifrResponse($res);
        }

        $id = Request::param('id');
        $data = [];
        if($id){
            $data = Db::table('wechat')->where('id',$id)->find();
        }
        $field = [
            ['label'=>'','name'=>'id','type'=>'hidden'],
            ['label'=>'微信名称','name'=>'name'],
            ['label'=>'APPID','name'=>'appid'],
            ['label'=>'APP_SECRET','name'=>'appsecret'],
            ['label'=>'原始id','name'=>'wechat_id'],
            ['label'=>'Token','name'=>'token','type'=>'random_str','length'=>32,'tips'=>'必须为英文或数字，长度为3-32字符,不填将由系统默认生成'],
            ['label'=>'EncodingAESKey','name'=>'encode_asc_key','type'=>'random_str','length'=>43,'tips'=>'消息加密密钥由43位字符组成,不填将由系统默认生成'],
            ['label'=>'状态','name'=>'status','type'=>'radio','options'=>[
                0=>'关闭',1=>'开启'
            ]],
        ];
        return parent::_buildModalEditForm('微信编辑',$field,$data);
    }
    
    public function accInfo()
    {
        $id = Request::param('id');
        $data = Db::table('wechat')->where('id',$id)->find();

        $data['ip']  = Request::server()['SERVER_ADDR'];
        $data['url'] = sprintf('http://%s/wechat/%s/verify',Request::host(),$data['id']);
        $this->assign('data',$data);
        return view('accInfo');
    }

    public function del()
    {
        $id = Request::param('id');
        Utils::rowDel('wechat',$id,'id',true);
    }
}
